package com.example.springbootdemo.handler;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootdemo.exception.BusinessResponseEnum;
import com.example.springbootdemo.bean.response.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理匿名用户无权访问
 * 用户访问受保护的资源，但是用户没有通过认证则会进入这个处理器
 * @author hh
 * @date 2022/1/27
 */
@Slf4j
@Component
public class UnauthorizedEntryPointHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.warn("用户需要登录，访问[{}]失败", request.getRequestURI());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(ResponseInfo.fail(BusinessResponseEnum.AUTHENTICATION_FAILED)));
    }

}
